package com.zcw.rabbitmq.chatroomv2;

import com.rabbitmq.client.BuiltinExchangeType;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.zcw.rabbitmq.util.RabbitConnectionUtil;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 聊天室相关类
 */
public class ChatRoom {

    public static Channel channel;
    public static String queue; // 没有初始化

    // 获取群聊

    /**
     * 获取聊天室
     * @param roomName 聊天室名称，用于聊天室的唯一标识
     * @param userName 用户名，用于声明队列，确保队列的唯一性
     * @return
     */
    public static Channel getChatRoom(String roomName, String userName){
        // 获取连接
        Connection connection = RabbitConnectionUtil.getSingleRabbitConnection();
        String queueName = userName;
        try {
            // 创建信道
            if (channel == null) {
                channel = connection.createChannel();
            }
            // 声明交换机
            channel.exchangeDeclare(roomName, BuiltinExchangeType.FANOUT, true);
            // 声明队列
            if (queue == null) {
                queue = channel.queueDeclare(queueName,false,false,false,null).getQueue();
            }
            System.out.println("queuename:" + queue);
            // 队列绑定到交换机
            channel.queueBind(queue, roomName, ""); // 将该队列绑定到交换机上
            return  channel;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

}
